package day10.gec.线程通信3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Shower4{
    int count = 1;

    //创建锁对象
    ReentrantLock lock = new ReentrantLock();

    //三个锁
    Condition c1 ;
    Condition c2 ;
    Condition c3 ;

    //构造器
    public Shower4() {
        //获得锁
        c1 = lock.newCondition();
        c2 = lock.newCondition();
        c3 = lock.newCondition();
    }

    public void show() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            lock.lock();
            while(count != 1) {
                c1.await();//等待 其实是将此线程进入暂停
            }

            Thread.sleep(10);
            System.out.println("我是中国人");

            count = 2;
            c2.signal();
            lock.unlock();

        }
    }

    public void show2() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            lock.lock();
            while(count != 2) {
                c2.await();//c2进入暂停
            }

            Thread.sleep(10);
            System.out.println("世界那么大");

            count = 3;
            c3.signal();//唤醒c3线程
            lock.unlock();

        }
    }

    public void show3() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            lock.lock();
            while(count != 3) {
                c3.await();//c3进入暂停
            }

            Thread.sleep(10);
            System.out.println("我想去看看");

            count = 1;
            c1.signal();//唤醒c1线程
            lock.unlock();

        }
    }
}

public class ShowerDemo4 {
    public static void main(String[] args) {
        final Shower4 s = new Shower4();
        new Thread() {

            @Override
            public void run() {
                try {
                    s.show();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }.start();

        new Thread() {

            @Override
            public void run() {
                try {
                    s.show2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }.start();

        new Thread() {

            @Override
            public void run() {
                try {
                    s.show3();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }.start();
    }
}